import { useCopilotChat } from "@copilotkit/react-core";
import { useEffect, useRef } from "react";

export default function ToolEventsListener() {
  const { visibleMessages, isLoading } = useCopilotChat();
  const lastToolEventCount = useRef(0);

  // 工具事件筛选逻辑
  const toolEvents = visibleMessages.filter(
    (msg: any) =>
      msg.role === "tool" ||
      (msg.type && msg.type === "ActionExecutionMessage") 
  );

  useEffect(() => {
    // 只打印新出现的工具事件
    if (toolEvents.length > lastToolEventCount.current) {
      const newEvents = toolEvents.slice(lastToolEventCount.current);
      newEvents.forEach(event => {
        console.log("工具事件:", event);
      });
      lastToolEventCount.current = toolEvents.length;
    }
  }, [toolEvents]);

  // 只在 isLoading 时查找最新的 ActionExecutionMessage
  let toolName: string | undefined;
  if (isLoading) {
    const latestToolMsg = [...visibleMessages].reverse().find(
      (msg: any) => msg.type === "ActionExecutionMessage"
    );
    toolName = latestToolMsg?.name;
  }

  return (
    <>
      {/* 只在工具调用进行中显示提示 */}
      {isLoading && toolName && (
        <div className="fixed top-4 left-1/2 -translate-x-1/2 z-50 bg-yellow-100 text-yellow-800 px-4 py-2 rounded shadow">
          助手正在调用「{toolName}」工具...
        </div>
      )}
    </>
  );
}